//
//  rec_video.c
//  myffmpegdemo1
//
//  Created by yuanxuzhen on 2021/4/6.
//

#include "rec_video.h"
static int rec_status = 0;

void set_status(int status);
AVFormatContext* open_dev();
void read_data(AVFormatContext *fmt_ctx, FILE *outfile);

void rec_video(){
    
    //context
    AVFormatContext* format_context = NULL;
    
    av_log_set_level(AV_LOG_DEBUG);
    
    rec_status = 1;
    
    
    char* url = "/Users/yuanxuzhen/study/mac/myffmpegdemo1/myffmpegdemo1/output/video.yuv";
    //创建文件
    FILE *out_file = fopen(url, "wb+");
    if(!out_file){
        printf("Error, Failed to open file!\n");
        goto __ERROR;
    }
    
    //打开设备
    format_context = open_dev();
    if(!format_context){
        printf("Error, Failed to open device!\n");
        goto __ERROR;
    }
    
    //encode
    read_data(format_context, out_file);
    
    
__ERROR:
    
    if(format_context){
        avformat_close_input(&format_context);
        format_context = NULL;
    }
    
    if(out_file){
        fclose(out_file);
    }
    
    av_log(NULL, AV_LOG_DEBUG, "finish!\n");
    return;
}




void set_status(int status){
    rec_status = status;
}




AVFormatContext* open_dev(){
    int ret = 0;
    char error[1024] = {0, };
    AVFormatContext* format_context = NULL ;
    char *devicename="0:";
    AVDictionary *options = NULL;
    avdevice_register_all();
    AVInputFormat * iformat = av_find_input_format("avfoundation");
    
    av_dict_set(&options, "video_size", "640x480", 0);
    av_dict_set(&options, "framerate", "30", 0);
    av_dict_set(&options, "pixel_format", "nv12", 0);

    ret = avformat_open_input(&format_context, devicename, iformat, &options);
    av_dump_format(format_context, 0, devicename, 0);
    if(ret < 0){
        av_strerror(ret, error, 1024);
        printf(stderr, "Failed to open audio devices, [%d] %s\n", ret, error);
        return NULL;
    };
    return format_context;
}



void read_data(AVFormatContext *fmt_ctx,
                          FILE *outfile){
    int ret = 0;
    AVPacket pkt;
    
    while ((ret = av_read_frame(fmt_ctx, &pkt)) == 0 || ret == -35) {
        if(!rec_status){
            break;
        }
        if(ret == -35){
            usleep(100);
            continue;
        }
        fwrite(pkt.data, 460800, 1, outfile);
        printf("pkt, pkt.size=%d!\n", pkt.size);
        fflush(outfile);
        av_packet_unref(&pkt);
    }
    
}


